package cn.hchaojie.ssm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

public class LoginInterceptor implements HandlerInterceptor {
	Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		
		// 从session里面取用户信息
		String user = (String) request.getSession().getAttribute("user");
		// 如果有，说明登陆了，返回true
		if (user != null && user.length() > 0) {
			logger.debug("用户已登陆，放行。。。");
			
			return true;
		} else {
			logger.debug("用户未登陆，跳到登陆界面。。。");
			
			// 没有的话返回false，同时跳到登陆界面
			request.getRequestDispatcher("/WEB-INF/pages/login.jsp").forward(request, response);
			return false;
		}
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
	}

}
